using System;
using System.Collections.ObjectModel;
using System.Windows.Threading;

namespace EMan.BL.Threading
{
  public class DispatchedCollection< T > : ObservableCollection< T >
  {
    private readonly Dispatcher _dispatcher;

    public DispatchedCollection( Dispatcher dispatcher )
    {
      _dispatcher = dispatcher;
    }

    protected override void SetItem( int index, T item )
    {
      if( _dispatcher.CheckAccess() )
        base.SetItem( index, item );
      else
        _dispatcher.Invoke( DispatcherPriority.Send, new Action< int, T >( SetItem ), index, new object[] {item} );
    }

    protected override void RemoveItem( int index )
    {
      if( _dispatcher.CheckAccess() )
        base.RemoveItem( index );
      else
        _dispatcher.Invoke( DispatcherPriority.Send, new Action< int >( RemoveItem ), index );
    }

    protected override void ClearItems()
    {
      if( _dispatcher.CheckAccess() )
        base.ClearItems();
      else
        _dispatcher.Invoke( DispatcherPriority.Send, new Action( ClearItems ) );
    }

    protected override void InsertItem( int index, T item )
    {
      if( _dispatcher.CheckAccess() )
        base.InsertItem( index, item );
      else
        _dispatcher.Invoke( DispatcherPriority.Send, new Action< int, T >( InsertItem ), index, new object[] {item} );
    }

    protected override void MoveItem( int oldIndex, int newIndex )
    {
      if( _dispatcher.CheckAccess() )
        base.MoveItem( oldIndex, newIndex );
      else
        _dispatcher.Invoke( DispatcherPriority.Send, new Action< int, int >( MoveItem ), oldIndex, new object[] {newIndex} );
    }
  }
}